// lib/base/requests.ts
import { API_CONFIG } from "../api/config";
import type { ApiResponse } from "../types";

/**
 * 请求选项接口
 */
interface RequestOptions {
  withAuth?: boolean;
}

/**
 * 基础服务类
 * 提供对 HTTP 客户端的基础封装，实现通用的 HTTP 请求方法
 * 其他服务类可以继承此类来实现具体的业务逻辑
 * @abstract
 */
export abstract class BaseService {
  /**
   * 发送 GET 请求
   * @param {string} url - 请求URL
   * @param {RequestOptions} options - 请求选项
   * @returns {Promise<ApiResponse<T>>} API响应
   */
  protected async get<T>(url: string, options: RequestOptions = { withAuth: true }): Promise<ApiResponse<T>> {
    const headers = this.getHeaders(options);
    console.log(`GET请求 ${url} 的请求头:`, headers);
    const response = await fetch(`${API_CONFIG.baseUrl}${url}`, {
      method: 'GET',
      headers,
    });
    return this.handleResponse<T>(response);
  }

  /**
   * 发送 POST 请求
   * @param {string} url - 请求URL
   * @param {any} data - 请求数据
   * @param {RequestOptions} options - 请求选项
   * @returns {Promise<ApiResponse<T>>} API响应
   */
  protected async post<T>(url: string, data?: any, options: RequestOptions = {}): Promise<ApiResponse<T>> {
    const headers = this.getHeaders(options);
    const response = await fetch(`${API_CONFIG.baseUrl}${url}`, {
      method: 'POST',
      headers,
      body: data ? JSON.stringify(data) : undefined,
    });
    return this.handleResponse<T>(response);
  }

  /**
   * 发送 PUT 请求
   * @param {string} url - 请求URL
   * @param {any} data - 请求数据
   * @param {RequestOptions} options - 请求选项
   * @returns {Promise<ApiResponse<T>>} API响应
   */
  protected async put<T>(url: string, data?: any, options: RequestOptions = {}): Promise<ApiResponse<T>> {
    const headers = this.getHeaders(options);
    const response = await fetch(`${API_CONFIG.baseUrl}${url}`, {
      method: 'PUT',
      headers,
      body: data ? JSON.stringify(data) : undefined,
    });
    return this.handleResponse<T>(response);
  }

  /**
   * 发送 DELETE 请求
   * @param {string} url - 请求URL
   * @param {RequestOptions} options - 请求选项
   * @returns {Promise<ApiResponse<T>>} API响应
   */
  protected async delete<T>(url: string, options: RequestOptions = {}): Promise<ApiResponse<T>> {
    const headers = this.getHeaders(options);
    const response = await fetch(`${API_CONFIG.baseUrl}${url}`, {
      method: 'DELETE',
      headers,
    });
    return this.handleResponse<T>(response);
  }

  /**
   * 获取请求头
   * @param {RequestOptions} options - 请求选项
   * @returns {HeadersInit} 请求头
   * @private
   */
  private getHeaders(options: RequestOptions): HeadersInit {
    const headers: HeadersInit = {
      'Content-Type': 'application/json',
    };

    if (options.withAuth) {
      const token = this.getAuthToken();
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }
    }

    return headers;
  }

  /**
   * 获取认证令牌
   * @returns {string | null} 认证令牌
   * @protected
   */
  protected getAuthToken(): string | null {
    if (typeof window !== "undefined") {
      // 从 cookie 获取
      const cookies = document.cookie.split(';');
      const tokenCookie = cookies.find(cookie => cookie.trim().startsWith('access_token='));
      if (tokenCookie) {
        return tokenCookie.split('=')[1];
      }
    }
    return null;
  }

  /**
   * 处理响应
   * @param {Response} response - 响应对象
   * @returns {Promise<ApiResponse<T>>} API响应
   * @private
   */
  private async handleResponse<T>(response: Response): Promise<ApiResponse<T>> {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const rawData = await response.json();
    
    // 构造符合 ApiResponse 接口的响应
    const apiResponse: ApiResponse<T> = {
      code: response.ok ? 200 : response.status,
      data: rawData,
      message: rawData.message || '请求成功'
    };
    
    return apiResponse;
  }
}
